package com.itheima.reggie.service.impl;

import com.itheima.reggie.dao.ShoppingCartDao;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartDao shoppingCartDao;
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
//        判断菜品是否存在
        ShoppingCart dbshoppingCart=shoppingCartDao.find(shoppingCart);
        if (dbshoppingCart==null){
            //        不存在创建
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartDao.add(shoppingCart);
            dbshoppingCart=shoppingCart;
        }else {
            //        存在数量加
            dbshoppingCart.setNumber(dbshoppingCart.getNumber()+1);
            shoppingCartDao.update(dbshoppingCart);
        }

        return dbshoppingCart;
    }

    @Override
    public List<ShoppingCart> findCart(Long userId) {
        List<ShoppingCart>shoppingCarts=shoppingCartDao.findCart(userId);
        return shoppingCarts;
    }

    @Override
    public void clean(Long userId) {
        shoppingCartDao.deleteAll(userId);
    }
}
